<template>
  <div style="background-color:white">
    <UploadDialog ref="uploadDialog"/>
    <el-row class="bottom-space">
      <el-col :span="6">
        <el-button type="success" size="small" v-on:click="importBook(null)">导入图书</el-button>
      </el-col>
      <el-col :span="18">
        <div style="width: 420px; float: right">
          <el-input v-model="termBookMetadata.name" placeholder="请输入图书名称" size="small"
                    @keyup.enter.native="searchEnterFun($event)">
            <i class="el-input__icon el-icon-search" slot="prefix"></i>
            <el-button :icon="appendIcon" slot="append" v-on:click="switchAppend"></el-button>
          </el-input>
        </div>
        <div id="advance"
             style="padding: 10px; float: right;"
             v-if="showAdvance">
          <div>
            <div style="margin-top: 20px; display: flex;">
              <div class="advancedSearchLabel">图书级别</div>
              <div style="width: 217px">
                <el-select v-model="termBookMetadata.category" clearable filterable placeholder="请选择图书级别">
                  <el-option value="0" label="名词委员会"></el-option>
                  <el-option value="1" label="卫健委发布标准"></el-option>
                  <el-option value="2" label="教材"></el-option>
                  <el-option value="3" label="专著"></el-option>
                </el-select>
              </div>
            </div>
          </div>
          <div>
            <div style="margin-top: 10px; display: flex;">
              <div class="advancedSearchLabel">图书版本</div>
              <div style="width: 217px">
                <el-input placeholder="请输入图书版本" @keyup.enter.native="searchEnterFun($event)"
                          v-model="termBookMetadata.version"></el-input>
              </div>
            </div>
          </div>
          <div>
            <div style="margin-top: 10px; display: flex;">
              <div class="advancedSearchLabel">图书ISBN号</div>
              <div style="width: 217px">
                <el-input placeholder="请输入图书ISBN号" @keyup.enter.native="searchEnterFun($event)"
                          v-model="termBookMetadata.isbn"></el-input>
              </div>
            </div>
          </div>
          <div>
            <div style="margin-top: 10px; display: flex;">
              <div class="advancedSearchLabel">状态</div>
              <div style="width: 217px">
                <el-select v-model="termBookMetadata.status" clearable filterable placeholder="请选择状态">
                  <el-option value="0" label="导入失败"></el-option>
                  <el-option value="1" label="导入成功"></el-option>
                  <el-option value="2" label="自检有冲突"></el-option>
                  <el-option value="3" label="自检完成"></el-option>
                  <el-option value="6" label="自检失败"></el-option>
                </el-select>
              </div>
            </div>
          </div>
          <div>
            <div style="margin-top: 10px; display: flex;">
              <div class="advancedSearchLabel">导入人</div>
              <div style="width: 217px">
                <el-input placeholder="请输入导入人" @keyup.enter.native="searchEnterFun($event)"
                          v-model="termBookMetadata.createdBy"></el-input>
              </div>
            </div>
          </div>
          <div>
            <div style="margin-top: 10px; display: flex;">
              <div class="advancedSearchLabel">导入时间</div>
              <div style="width: 217px">
                <el-date-picker v-model="termBookMetadata.importDate" :picker-options="pickerOptions" align="right"
                                end-placeholder="截止日期"
                                range-separator="至" value-format="yyyy-MM-dd"
                                size="small" start-placeholder="开始日期" style="width: 100%"
                                type="daterange" unlink-panels>
                </el-date-picker>
              </div>
            </div>
          </div>
          <div style="margin-top: 30px; right: 10px;">
            <el-row>
              <el-col :offset="6"
                      :span="6">
                <div style="margin-left: 90px;height: 32px; width: 88px;">
                  <el-button size="small"
                             v-on:click="advanceCancel">取 消
                  </el-button>
                </div>
              </el-col>
              <el-col :offset="2"
                      :span="2">
                <div style="margin-left: 30px;height: 32px; width: 88px;">
                  <el-button size="small"
                             v-on:click="reset">重置
                  </el-button>
                </div>
              </el-col>
              <el-col :offset="2"
                      :span="2">
                <div div
                     style="margin-left: 30px;height: 32px; width: 88px;">
                  <el-button size="small"
                             type="success"
                             v-on:click="advanceConfirm">确 定
                  </el-button>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-col>
    </el-row>
    <el-row>
      <el-table highlight-current-row :data="tableData" border style="width: 100%;" stripe :height="tableHeight">
        <el-table-column label="书本名称" min-width="160" prop="name">
        </el-table-column>
        <el-table-column label="书本级别" min-width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.category === 0">名词委员会</span>
            <span v-if="scope.row.category === 1">卫健委发布标准</span>
            <span v-if="scope.row.category === 2">教材</span>
            <span v-if="scope.row.category === 3">专著</span>
          </template>
        </el-table-column>
        <el-table-column label="版本" min-width="120" prop="version"></el-table-column>
        <el-table-column label="ISBN" min-width="160" prop="isbn"></el-table-column>
        <el-table-column :show-overflow-tooltip="false" label="状态" min-width="120" prop="status">
          <template slot-scope="scope">
            <span v-if="scope.row.status === 0" style="color: #EC0000">导入失败
              <el-popover trigger="hover" :content="failureReason" v-on:show="openShow(scope.$index)">
                <el-button type="text" slot="reference"><a style="color: #EC0000">详情</a> </el-button>
              </el-popover><i class="el-icon-warning-outline el-icon--right"></i>
              <el-link type="primary" @click.prevent="importBook(scope.row.id)">重新上传</el-link>
            </span>
            <span v-if="scope.row.status === 1" style="color: #FF8C00">导入成功</span>
            <span v-if="scope.row.status === 2" style="color: darkred;">
              自检有冲突<el-link type="primary" @click.prevent="detailById(scope.row.id, scope.row.status)">查看详情</el-link>
            </span>
            <span v-if="scope.row.status === 3">已入中间术语库</span>
            <span v-if="scope.row.status === 4">图书导入中</span>
            <span v-if="scope.row.status === 5">图书自检中</span>
            <span v-if="scope.row.status === 6" style="color: #EC0000">自检失败
              <el-popover trigger="hover" :content="failureReason" v-on:show="openShow(scope.$index)">
                <el-button type="text" slot="reference"><a style="color: #EC0000">详情</a> </el-button>
              </el-popover><i class="el-icon-warning-outline el-icon--right"></i>
              <el-link type="primary" @click.prevent="selfChecking(scope.row.id, scope.row.category)">重新自检</el-link>
            </span>
            <span v-if="scope.row.status === 7" style="color: darkred;">与标准术语对比中</span>
            <span v-if="scope.row.status === 8" style="color: darkred;">
              与标准术语对比失败<el-popover trigger="hover" :content="failureReason" v-on:show="openShow(scope.$index)">
                <el-button type="text" slot="reference"><a style="color: #EC0000">详情</a> </el-button>
              </el-popover><i class="el-icon-warning-outline el-icon--right"></i>
            </span>
            <span v-if="scope.row.status === 9" style="color: darkred;">
              与标准术语有冲突
            </span>
            <span v-if="scope.row.status === 10" style="color: darkred;">已入标准术语</span>
            <span v-if="scope.row.groupConflict != 0">
              <el-link type="primary" @click.prevent="downloadTerm(scope.row.id)">下载</el-link>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="导入时间" min-width="160" prop="createdTime" :formatter="dateFormat"></el-table-column>
        <el-table-column label="导入者" min-width="120" prop="createdBy"></el-table-column>
        <el-table-column label="操作" min-width="180">
          <template slot-scope="scope">
            <el-link type="primary" @click.prevent="metadataById(scope.row.id, scope.row.metadata, scope.row.category)">
              元数据
            </el-link>
            <el-link type="primary" @click.prevent="detailById(scope.row.id, scope.row.status)">查看</el-link>
            <el-link v-if="scope.row.status == 1 || scope.row.status == 6" type="danger"
                     @click.prevent="selfChecking(scope.row.id, scope.row.category)">图书自检
            </el-link>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row>
      <el-pagination :page-size="pageSize" :total="totalNum" @current-change="handleCurrentChange" background
                     layout="total, prev, pager, next, jumper" style="text-align: right;margin-top: 10px"
                     v-if="multiplePages"></el-pagination>
    </el-row>
  </div>
</template>

<script>
import UploadDialog from './UploadDialog'
import moment from "moment";

export default {
  components: {
    UploadDialog
  },
  data() {
    return {
      appendIcon: "el-icon-caret-bottom",
      showAdvance: false,
      oplogVisible: false,
      bookMetadataId: '',
      uploadVisible: false,
      multiplePages: true,
      noData: true,
      totalNum: 0,
      currentPage: 0,
      pageSize: 10,
      tableData: [],
      tableHeight: '',
      failureReason: '',
      status: '',
      termBookMetadata: {},
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
    }
  },
  methods: {
    importBook: function (id) {
      this.uploadVisible = true;
      this.$refs.uploadDialog.bookMetadataId = id
    },
    handleCurrentChange: function (val) {
      this.currentPage = val - 1;
      this.getTableData();
    },
    dateFormat: function (row, column) {
      const date = row[column.property]
      if (date === undefined) {
        return ''
      }
      return moment(date).format("YYYY-MM-DD  HH:mm:ss")
    },
    searchEnterFun(e) {
      const keyCode = window.event ? e.keyCode : e.which;
      if (keyCode === 13) {
        this.currentPage = 0;
        this.getTableData();
      }
    },
    switchAppend: function () {
      if (this.showAdvance) {
        this.showAdvance = false;
        this.appendIcon = "el-icon-caret-bottom";
      } else {
        this.showAdvance = true;
        this.appendIcon = "el-icon-caret-top";
      }
    },
    openShow: function (index) {
      this.failureReason = this.tableData[index].failureReason
    },
    getTableData: function () {
      this.termBookMetadata.type = 'original';
      this.termBookMetadata.currentPage = this.currentPage;
      this.termBookMetadata.pageSize = this.pageSize;
      let param = new URLSearchParams();
      param.append("termBookMetadata", JSON.stringify(this.termBookMetadata));
      this.axios.post('/pmph/action/term/selectBookMetadata', param).then((response) => {
        if (response.data.isfinish) {
          clearInterval(this.timer);
        }
        this.noData = response.data.totalNum <= 0;
        this.tableData = response.data.tableData;
        this.totalNum = response.data.totalNum;
      }).catch((error) => {
        clearInterval(this.timer);
        console.error(error);
        this.tableData = [];
        this.noData = true;
        this.$message.error("未能请求到数据");
      })
    },
    metadataById(id, metadata, category) {
      this.$router.push({
        path: "/term/Metadata",
        query: {
          id: id,
          metadata: metadata,
          category: category
        }
      });
    },
    detailById(id, status) {
      this.$router.push({
        path: "/term/bookTermDetail",
        query: {
          id: id,
          status: status
        }
      });
    },
    selfChecking(id, category) {
      // 如果图书未设置书本级别,不让自检
      if (UTIL.isEmpty(category) && category !== 0) {
        this.$message.warning("请先在元数据页面设置书本级别");
        return;
      }
      this.axios.get('/pmph/action/term/selfChecking', {
        params: {
          id: id
        }
      }).then((response) => {
        this.getTableData();
        this.timer = setInterval(this.getTableData, 3000);
        this.noData = response.data.totalNum <= 0;
        this.tableData = response.data.tableData;
        this.totalNum = response.data.totalNum;
      })
    },
    downloadTerm(id) {
      window.location.href = '/pmph/action/term/downloadTerm?id=' + id;
    },
    reset() {
      this.termBookMetadata.name = '';
      this.termBookMetadata.category = '';
      this.termBookMetadata.version = '';
      this.termBookMetadata.isbn = '';
      this.termBookMetadata.status = '';
      this.termBookMetadata.createdBy = '';
      this.termBookMetadata.importDate = '';
    },
    advanceCancel: function () {
      this.showAdvance = false;
    },
    advanceConfirm: function () {
      this.currentPage = 0;
      this.getTableData();
      this.showAdvance = false;
    }
  },
  activated() {
    clearInterval(this.timer);
    if (!this.$route.meta.isUseCache) {
      this.getTableData();
      this.timer = setInterval(this.getTableData, 3000);
    }
  },
  created() {
    this.tableHeight = CONST.WORKSPACE_HEIGHT - 150;
    this.getTableData();
  }
}
</script>

<style scoped>
.bottom-space {
  margin-bottom: 10px;
}
</style>
